from fastapi import APIRouter, HTTPException
from fastapi.responses import JSONResponse, StreamingResponse

from app.schemas.crawler import StartCrawlerRequest
from app.services.crawlerService import CrawlerService

router = APIRouter()

@router.post("/startCrawler")
async def start_crawler(request: StartCrawlerRequest):
    try:
        response = await CrawlerService.start_crawler(
            platform=request.platform,
            keywords=request.keywords,
            login_type="cookie",
            crawl_type="search",
            save_option="json"
        )

        if isinstance(response, (StreamingResponse, JSONResponse)):
            return response
        else:
            raise HTTPException(status_code=500, detail="系统错误: 爬虫服务返回了非预期的响应类型")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"系统错误: {str(e)}")

@router.get("/getTotalComments")
async def get_total_comments(keywords: str):
    try:
        result = await CrawlerService.get_total_comments(keywords)
        if result['status'] == 'success':
            return {"status": "success", "totalComments": result['totalComments']}
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"系统错误: {str(e)}")

@router.get("/getDBBase")
async def get_db_base():
    try:
        result = await CrawlerService.get_DB_basement()
        if result['status'] == 'success':
            return {"status": "success", "dbInfo": result['dbInfo']}
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"系统错误: {str(e)}") 